<?php

namespace App\Admin\Grid\Tools;

use App\Admin\Admin;
use Illuminate\Support\Collection;

class BatchActions extends AbstractTool
{
    /**
     * 批量操作按钮集
     *
     * @var Collection
     */
    protected $actions;

    /**
     * 允许删除
     *
     * @var bool
     */
    protected $enableDelete = true;

    /**
     * BatchActions constructor.
     */
    public function __construct()
    {
        $this->actions = new Collection();

        $this->appendDefaultAction();
    }

    /**
     * 追加默认的批量操作按钮(只有批量删除)
     *
     * return void
     */
    protected function appendDefaultAction()
    {
        $this->add('删除', new BatchDelete(), 'delete');
    }

    /**
     * 禁用批量删除
     *
     * @return $this
     */
    public function disableDelete()
    {
        $this->enableDelete = false;
        $this->actions->shift();

        return $this;
    }

    /**
     * 添加一个批量操作按钮
     *
     * @param string      $title
     * @param BatchAction $abstract
     * @param string      $id 用来绑定js时间的class后缀
     *
     * @return $this
     */
    public function add($title, BatchAction $abstract, $id = '')
    {
        $id = $id ?: $id = $this->actions->count();

        $abstract->setId($id);

        $this->actions->push(compact('id', 'title', 'abstract'));

        return $this;
    }

    /**
     * 批量操作按钮的js
     *
     * @return void
     */
    protected function setUpScripts()
    {
        Admin::script($this->script());

        $this->actions = $this->actions->map(function ($action) {
            /**
             * @var BatchAction $abstract
             */
            $abstract = $action['abstract'];
            $abstract->setResource($this->grid->resource());
            $action['resource'] = '/' . $abstract->getResource() . '/';

            Admin::script($abstract->script());

            return $action;
        });
    }

    /**
     * 批量操作对应的js
     *
     * @return string
     */
    protected function script()
    {
        return '';
    }

    /**
     * 生成批量操作按钮组
     *
     * @return string
     * @throws \Throwable
     */
    public function render()
    {
        // 调整到disableDelete中
        // if (!$this->grid->allowBatchDeletion() || !$this->enableDelete) {
        //     $this->actions->shift();
        // }

        if ($this->actions->isEmpty()) {
            return '';
        }

        $this->setUpScripts();

        return view('admin.grid.batch_actions', ['actions' => $this->actions])->render();
    }

    /**
     * 返回是否有批量操作按钮
     *
     * @return bool
     */
    public function hasActions()
    {
        return !$this->actions->isEmpty();
    }
}
